package com.zyf.service;

import cn.hutool.core.io.FileUtil;
import com.zyf.utils.ListUtil;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.epub.EpubReader;

import java.io.*;
import java.util.*;

/**
 * 处理语音
 */
public class HandleTxtService {

    /**
     * 处理文档
     *
     * @param folderPath
     */
    public void handleTxt(String folderPath) throws Exception {
        List<File> txtList = FileUtil.loopFiles(folderPath, file -> file.isFile() && file.getName().endsWith(".txt"));
        for (File file : txtList) {
            handleTxt(file);
        }
    }

    /**
     * 获取最后的文本
     */
    public String handleTxt(File txtFile) throws IOException {
        String[] punctuation = {"。", "，", "？", "！"};
        List<String> punctuations = Arrays.asList(punctuation);
        InputStream inputstream = null;
        String filename = txtFile.getName().substring(0, txtFile.getName().indexOf("."));
        BufferedReader reader = null;
        String temp = "";
        StringBuffer buffer_final = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(txtFile)));
            while ((temp = reader.readLine()) != null) {
                if (temp.contains("《")) {
                    String restr = temp.replace("《", "").replace("》", "").trim();
                    buffer_final.append(restr);
                    buffer_final.append("\n");
                    buffer_final.append(filename);
                    buffer_final.append("\n");
                } else if (temp.contains("*********") || temp.contains("td")) {
                    buffer_final.append(temp.trim());
                    buffer_final.append("\n");
                } else {
                    subContentByLength(temp.trim(), buffer_final);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputstream != null) {
                try {
                    inputstream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //写入文件
        FileWriter writer = null;
        String finalsrt = "";
        try {
            finalsrt = txtFile.getAbsolutePath().replace(".", "_final.");
            writer = new FileWriter(finalsrt, false);
            writer.write(buffer_final.toString());
            return finalsrt;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }
    }

    /**
     * 递归处理字符串
     *
     * @param content
     * @param buffer
     */
    private void subContentByLength(String content, StringBuffer buffer) {
        //超过16个汉字进行分行
        String[] punctuation = {"。", "，", "？", "！", "；"};
        List<String> punctuations = Arrays.asList(punctuation);
        int length = content.length();
        if (length > 16) {
            boolean isMatch = false;
            for (int i = 15; i >= 0; i--) {
                String lastChar = content.substring(i, i + 1);
                if (punctuations.contains(lastChar)) {
                    String newContent = content.substring(0, i + 1);
                    buffer.append(newContent);
                    buffer.append("\n");
                    content = content.substring(i + 1);
                    isMatch = true;
                    break;
                }
            }
            if (isMatch) {
                subContentByLength(content, buffer);
            } else {
                buffer.append(content);
                buffer.append("\n");
            }
        } else {
            buffer.append(content);
            buffer.append("\n");
        }

    }


    public boolean isChinese(String str) {
        boolean isChinese = true;
        for (char c : str.toCharArray()) {
            if (!Character.isIdeographic(c)) {
                isChinese = false;
                break;
            }
        }
        return isChinese;
    }


    /**
     * 获取古诗词的前四行
     */
    public void handleBeforeFourLines(String folderPath, int lines) throws IOException {
        List<File> txtList = FileUtil.loopFiles(folderPath, file -> file.isFile() && file.getName().endsWith(".txt"));
        for (File file : txtList) {
            handleTxtByLines(file, lines);
        }
    }

    private String handleTxtByLines(File txtFile, int lines) throws IOException {
        InputStream inputstream = null;
        String filename = txtFile.getName().substring(0, txtFile.getName().indexOf("."));
        BufferedReader reader = null;
        String temp = "";
        StringBuffer buffer_final = new StringBuffer();
        try {
            int index = 0;
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(txtFile)));
            while ((temp = reader.readLine()) != null) {
                if (temp.contains("*********")) {
                    index = 0;
                    buffer_final.append(temp.trim());
                    buffer_final.append("\n");
                } else {
                    if (index == lines) {
                        continue;
                    }
                    buffer_final.append(temp.trim());
                    buffer_final.append("\n");
                    index++;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputstream != null) {
                try {
                    inputstream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //写入文件
        FileWriter writer = null;
        String finalsrt = "";
        try {
            finalsrt = txtFile.getAbsolutePath().replace(".", "_final.");
            writer = new FileWriter(finalsrt, false);
            writer.write(buffer_final.toString());
            return finalsrt;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }
    }

    /**
     * 电子书epub 转为 txt
     *
     * @param folderPath
     */
    public void handleEpubToTxt(String folderPath) {
        List<File> srcFiles = FileUtil.loopFiles(folderPath, backfile -> backfile.isFile() && backfile.getName().endsWith(".epub"));
        for (File file : srcFiles) {
            String epubFilePath = file.getAbsolutePath();
            String txtFilePath = file.getName().replace(".epub", ".txt");
            try {
                // 使用 EPUB 读取器读取 EPUB 文件
                EpubReader epubReader = new EpubReader();
                Book book = epubReader.readEpub(new FileInputStream(epubFilePath));
                StringBuilder content = new StringBuilder();
                // 遍历书的所有章节
                for (int i = 0; i < book.getSpine().size(); i++) {
                    // 获取章节内容
                    String chapterContent = new String(book.getSpine().getSpineReferences().get(i).getResource().getData());
                    content.append(chapterContent);
                    content.append("\n");
                }
                // 将提取的内容写入 TXT 文件
                try (BufferedWriter writer = new BufferedWriter(new FileWriter(txtFilePath))) {
                    writer.write(content.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


        }

    }
}
